﻿using IOP.Extension.DependencyInjection;
using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace VkSample103
{
    [ModulePriority(ModulePriority.RenderGroup)]
    public class PipelineModule : VulkanModule, IVulkanRenderWapperModule
    {
        [Autowired]
        private ILogger<PipelineModule> _Logger { get; set; }

        public VulkanRenderWapper RenderWapper { get; set; }

        protected override async Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var lDevice = graphicsManager.VulkanDevice;
                var pipeCache = lDevice.PipelineCache;
                var disapatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
                var presentPass = disapatcher.SwapchainRenderPass;
                var area = RenderWapper.RenderArea;
                var basePath = AppContext.BaseDirectory;
                var shaders = Path.Combine(basePath, "Assets", "Shaders");
                var document = await JsonDocument.ParseAsync(File.OpenRead(Path.Combine(shaders, "Pipeline.json")));
                var pipelineJson = document.RootElement;

                var camera = graphicsManager.CreateCamera("main", new Vector3(0, 0f, 25.0f), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                camera.EncircleForX(Vector3.Zero, -20 * MathF.PI / 180.0f);
                float aspcet = (float)area.Width / area.Height;
                camera.SetProjectMatrix(-aspcet, 1.0f, 2.8f, 1000);
                camera.SetViewport(0, 0, area.Width, area.Height, 0.0f, 1.0f);
                camera.SetScissor(0, 0, area.Width, area.Height);

                graphicsManager.TryGetRenderGroup("Main", out IRenderGroup group);
                var mainGroup = group as PrimaryVulkanRenderGroup;
                var commonSetlayoutJson = pipelineJson.GetProperty("CommonDescriptorSetLayoutCreateOption").GetRawText();
                var discardSetLayoutJson = pipelineJson.GetProperty("DiscardDescriptorSetLayoutCreateOption").GetRawText();
                var pipeSetLayoutJson = pipelineJson.GetProperty("PipelineLayoutCreateOption").GetRawText();
                VulkanShaderInfo[] infos = new VulkanSPVShaderInfo[]
                {
                    new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "Vert", new FileInfo(Path.Combine(shaders,"vert.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "Frag", new FileInfo(Path.Combine(shaders, "frag.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "VertDiscard", new FileInfo(Path.Combine(shaders, "vertdiscard.spv"))),
                    new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "FragDiscard", new FileInfo(Path.Combine(shaders, "fragdiscard.spv")))
                };
                await Task.WhenAll(infos[0].LoadShader(), infos[1].LoadShader(), infos[2].LoadShader(), infos[3].LoadShader());
                var pipeline = graphicsManager.CreateEmptyPipeline("Common")
                    .BuildPipelineLayoutFromJson(commonSetlayoutJson, pipeSetLayoutJson)
                    .BuildUniformBuffer(0, 0, 80, SharingMode.Exclusive)
                    .BuildGraphicsPipelineFromJson(presentPass, pipeCache, new VulkanShaderInfo[] { infos[0], infos[1] }, pipelineJson.GetProperty("Pipeline").GetRawText());
                var discardPipeline = graphicsManager.CreateEmptyPipeline("Discard")
                    .BuildPipelineLayoutFromJson(discardSetLayoutJson, pipeSetLayoutJson)
                    .BuildUniformBuffer(0, 0, 80, SharingMode.Exclusive)
                    .BuildUniformBuffer(0, 1, 4, SharingMode.Exclusive)
                    .BuildGraphicsPipelineFromJson(presentPass, pipeCache, new VulkanShaderInfo[] { infos[2], infos[3] }, pipelineJson.GetProperty("Pipeline").GetRawText());
                var sCommand = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreateSecondaryCommandBuffer();
                var sCommand1 = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreateSecondaryCommandBuffer();
                var sGroup = graphicsManager.CreateSecondaryVulkanRenderGroup("Common", pipeline)
                    .Binding(mainGroup, sCommand, new VulkanSemaphore[0], new VulkanFence[0]);
                sGroup.SetCamera(camera);
                sGroup.CreateGroupRenderingAction((builder) => builder.UseMiddleware<Middleware>());
                sGroup.CreateItemRenderingAction((builder) => builder.UseMiddleware<ItemMiddleware>());

                var discard = graphicsManager.CreateSecondaryVulkanRenderGroup("Discard", discardPipeline)
                    .Binding(mainGroup, sCommand1, new VulkanSemaphore[0], new VulkanFence[0]);
                discard.SetCamera(camera);
                discard.CreateGroupRenderingAction((builder) => builder.UseMiddleware<Middleware>());
                discard.CreateItemRenderingAction((builder) => builder.UseMiddleware<ItemMiddleware>());

                RenderWapper.CreateAndCutScene<Scene>("Main", mainGroup, typeof(InputSystem), typeof(TransformSystem), typeof(LightSystem));
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            }
        }


        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
